import 'dart:async';
import 'dart:io';

import 'package:flutter_blue_plus/flutter_blue_plus.dart';

class BluetoothStateUtil {
  static BluetoothStateUtil? _instance;

  BluetoothAdapterState _adapterState = BluetoothAdapterState.unknown;
  late StreamSubscription<BluetoothAdapterState> _adapterStateStateSubscription;

  BluetoothStateUtil._();

  static BluetoothStateUtil get instance =>
      _instance ??= BluetoothStateUtil._();

  //蓝牙状态监听回调
  void bluetoothStateCallback() {
    _adapterStateStateSubscription =
        FlutterBluePlus.adapterState.listen((state) {
      _adapterState = state;
    });
  }

  //清除蓝牙监听
  void cancel() {
    _adapterStateStateSubscription.cancel();
  }

  // 获取蓝牙状态
  bool getBluetoothState() {
    return _adapterState == BluetoothAdapterState.on;
  }

  //请求打开蓝牙
  Future<void> turnOn() async {
    if (Platform.isAndroid) {
      await FlutterBluePlus.turnOn();
    }
  }
}
